<script setup lang="ts">
import { uploadAPI } from '@/apis/common';
import { createRentAPI, deleteEnterpriseAPI, deleteRentItemAPI, getEnterpriseListApi, getRentBuildingListAPI, getRentListAPI, outRentItemAPI } from '@/apis/enterprise';
import type { Datum, Enterprise, RentBuilding, RentParams } from '@/types/enterprise';
import { ElMessage, ElMessageBox, type FormInstance, type FormRules, type UploadRawFile, type UploadRequestOptions } from 'element-plus';
import { ref, watch } from 'vue';
import { useRouter } from 'vue-router';

// 带租房合同的嵌套类型
interface newEnterpriseListRent extends Enterprise {
  rentList: Datum[]
}

// 列表参数数据
const enterpriseParams = ref({
  name: '',
  page: 1,
  pageSize: 10
})
// 请求列表数据
const enterpriseList = ref<newEnterpriseListRent[]>()
const total = ref(0)
const getEnterpriseList = async () => {
  const res = await getEnterpriseListApi(enterpriseParams.value)
  // 添加数据
  enterpriseList.value = res.data.rows.map(item => ({
    ...item,
    rentList: []
  }))
  total.value = res.data.total
}
getEnterpriseList()

// 编辑
const router = useRouter()
const edit = (row: Enterprise) => {
  router.push({
    name: 'exterpriseAdd',
    params: { id: row.id }
  })
}
// 删除
const removeEnterprise = async (id: number) => {
  await ElMessageBox.confirm('此操作将永久删除该文件, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
  await deleteEnterpriseAPI(id)
  ElMessage.success('删除成功')
  getEnterpriseList()
}

// 合同 ----------------------------------------------------
const addFormRef = ref<FormInstance>()

const contractDialogVisible = ref(false) // 合同弹窗
// 可租楼宇列表
const rentBuildingList = ref<RentBuilding[]>()

// 合同表单数据
const rentForm = ref<RentParams>({
  buildingId: undefined, // 楼宇id
  startTime: '', 
  endTime: '',
  contractUrl: '',
  contractId: undefined,
  type: 0, // 操作类型，添加合同0，续签合同1
  enterpriseId: undefined
})
// 合同表单验证规则
const rentRules = ref<FormRules<RentParams>>({
  buildingId: [
    { required: true, message: '请选择楼宇', trigger: 'change' }
  ],
  endTime: [
    { required: true, message: '请选择租赁日期', trigger: 'blur' }
  ],
  contractId: [
    { required: true, message: '请上传合同文件' }
  ]
})
// 日期选择器
const dateRent = ref<string[] | undefined>([])
// 日期选择器选择后更新数据
watch(dateRent, (val) => {
  if (val) {
    rentForm.value.startTime = val[0]
    rentForm.value.endTime = val[1]
  } else {
    rentForm.value.startTime = ''
    rentForm.value.endTime = ''
  }
}, {deep: true})
const disabledDate = (time: Date) => {
  return time.getTime() < Date.now() - 1000 * 60 * 60 * 24
}
// 上传合同文件
const uploadRequest = async (options: UploadRequestOptions) => {
  const fd = new FormData()
  fd.append('file', options.file)
  fd.append('type', 'contract')
  const res = await uploadAPI(fd)
  rentForm.value.contractId = res.data.id
  rentForm.value.contractUrl = res.data.url
  addFormRef.value?.validateField('contractId')

  return res.data
}
// 合同文件 -删除
const onRemove = () => {
  rentForm.value.contractId = undefined
  rentForm.value.contractUrl = ''
  addFormRef.value?.validateField('contractId')
}
// 上传合同文件前校验
const beforeUpload = (rawFile: UploadRawFile) => {
    if (rawFile.size > 5 * 1024 * 1024) {
        ElMessage.error('文件大小不能超过5M')
        return false
    }
    return true
}
// 提交合同表单
const onSubmitContract = async () => {
  try {
    await addFormRef.value?.validate()
    await createRentAPI(rentForm.value)
    ElMessage.success('添加成功')
    closeContract()
  } catch (error) {
    
  }
}
// 弹框类型
const windowFlag = ref(false)
// 合同开启弹窗
const openContract = async (id: number) => {
  windowFlag.value = true // 添加合同弹窗
  contractDialogVisible.value = true
  // 获取可阻带楼宇
  // 添加楼宇 -- 新增合同
  const res = await getRentBuildingListAPI()
  rentBuildingList.value = res.data
  rentForm.value.enterpriseId = id
}

// 续租租赁 弹窗
const buildName = ref<string>('')
const addTimerRent = async (fRow: newEnterpriseListRent, rentRow: Datum) => {
  windowFlag.value = false // 续租合同弹窗
  contractDialogVisible.value = true
  // 回显数据
  const obj = fRow.rentList.find(item => item.id === rentRow.id) as Datum

  console.log(obj)
  rentForm.value.buildingId = obj.buildingId
  rentForm.value.enterpriseId = fRow.id
  dateRent.value = [obj.startTime, obj.endTime]
  rentForm.value.type = 1
  buildName.value = obj.buildingName
}

const fileList = ref([])
// 合同关闭弹窗
const closeContract = () => {
  dateRent.value = undefined
  addFormRef.value?.resetFields()
  rentForm.value.contractUrl = ''
  fileList.value = []
  contractDialogVisible.value = false
}

// 展开表单
const enterpriseRow = ref<newEnterpriseListRent>()
const expandRow = async (row: newEnterpriseListRent) => {
  const res = await getRentListAPI(row.id)
  row.rentList = res.data
  enterpriseRow.value = row
  console.log('1',row)
}
// 编辑
const outRent = async (row: Datum) => {
  await ElMessageBox.confirm('此操作将退租该合同, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
  await outRentItemAPI(row.id)
  row.status = 3
  ElMessage.success('退租成功')
}

// 删除租赁
const delRent = async (row: Datum, fRow: newEnterpriseListRent) => {
  await ElMessageBox.confirm('此操作将永久删除该合同, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
  await deleteRentItemAPI(row.id)
  fRow.rentList = fRow.rentList.filter(item => item.id !== row.id)
  ElMessage.success('删除成功')
}

</script>

<template>
  <div class="building-container">
    <!-- 搜索区域 -->
    <div class="search-container">
      <div class="search-label">企业名称：</div>
      <el-input @clear="getEnterpriseList()" v-model="enterpriseParams.name" clearable placeholder="请输入内容" class="search-main" />
      <el-button type="primary" @click="() => {enterpriseParams.page = 1; getEnterpriseList()}">查询</el-button>
    </div>
    <div class="create-container">
      <el-button type="primary" @click="$router.push('/exterpriseAdd')">添加企业</el-button>
    </div>
    <!-- 表格区域 -->
    <div class="table">
      <el-table style="width: 100%" :data="enterpriseList" @expand-change="expandRow" row-key="id">
        <!-- 新增：展开部分 -->
        <el-table-column type="expand" >
          <template #default="{ row }">
            <el-table :data="row.rentList">
              <el-table-column label="租赁楼宇" width="320" prop="buildingName" />
              <el-table-column label="租赁起始时间" prop="startTime" />
              <el-table-column label="合同状态" prop="status">
                <template #default="{row}">
                  <el-tag v-if="row.status === 0" type="warning">待生效</el-tag>
                  <el-tag v-else-if="row.status === 1" type="success">已生效</el-tag>
                  <el-tag v-else-if="row.status === 2" type="info">已到期</el-tag>
                  <el-tag v-else-if="row.status === 3" type="danger">已退租</el-tag>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="300">
                <template #default="{row: rentRow }">
                  <el-button size="small" type="primary" link @click="addTimerRent(row, rentRow)">续租</el-button>
                  <el-button @click="outRent(rentRow)" size="small" type="primary" link :disabled = "rentRow.status === 3">退租</el-button>
                  <el-button @click="delRent(rentRow, row)" size="small" type="primary" link :disabled = "rentRow.status !== 3">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </template>
        </el-table-column>
        <el-table-column type="index" label="序号" width="120" />
        <el-table-column prop="name" label="企业名称" width="320" />
        <el-table-column prop="contact" label="联系人" />
        <el-table-column prop="contactNumber" label="联系电话" />
        <el-table-column width="290" label="操作">
          <template #default="{row}">
            <el-button size="small" type="primary" @click="openContract(row.id)">添加合同</el-button>
            <el-button size="small" type="primary" @click="$router.push(`/exterpriseDetail/${ row.id }`)">查看</el-button>
            <el-button size="small" type="primary" @click="edit(row)">编辑</el-button>
            <el-button size="small" type="danger" @click="removeEnterprise(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="page-container">
      <el-pagination
        :size="[2, 4, 6, 8]"
        v-model:current-page="enterpriseParams.page" 
        v-model:page-size="enterpriseParams.pageSize"
        :total="total"
        layout="total, prev, pager, next, sizes, jumper" 
        @change="getEnterpriseList()" 
      />
    </div>
    <!-- 合同弹窗 -->
    <el-dialog :title="windowFlag ? '添加合同' : '续费合同'" width="600px" v-model="contractDialogVisible" @close="closeContract">
      <!-- 表单模版 -->
      <div class="form-container">
        <el-form ref="addFormRef" :model="rentForm" :rules="rentRules" label-position="top">
          {{ rentForm }}
          <el-form-item label="租赁楼宇" prop="buildingId">
            <el-select v-if="windowFlag" v-model="rentForm.buildingId" placeholder="请选择">
              <el-option v-for="item in rentBuildingList" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
            <el-input v-model="buildName" v-else disabled />
          </el-form-item>
          <el-form-item label="租赁起止日期" prop="endTime">
            <el-date-picker v-model="dateRent" type="daterange" range-separator="至" start-placeholder="开始日期"
              end-placeholder="结束日期" value-format="YYYY-MM-DD" :disabled-date="disabledDate" />
          </el-form-item>
          <el-form-item label="租赁合同" prop="contractId">
            <el-upload :file-list="fileList" accept=".doc, .pdf" :http-request="uploadRequest" @remove="onRemove" :before-upload="beforeUpload" >
              <el-button size="small" type="primary" plain>上传合同文件</el-button>
              <template #tip>
                <div class="el-upload__tip">支持扩展名：.doc .pdf, 文件大小不超过5M</div>
              </template>
            </el-upload>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer">
           <el-button @click="closeContract">取 消</el-button>
           <el-button type="primary" @click="onSubmitContract">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.building-container {
  padding: 20px;
}

.search-container {
  display: flex;
  align-items: center;
  border-bottom: 1px solid rgb(237, 237, 237, .9);
  ;
  padding-bottom: 20px;

  .search-label {
    width: 100px;
  }

  .search-main {
    width: 220px;
    margin-right: 10px;
  }
}

.create-container {
  margin: 10px 0px;
}

.page-container {
  padding: 4px 0px;
  text-align: right;
}

.form-container {
  padding: 0px 80px;
}
</style>